package com.example.lw;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.WebView;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import java.util.concurrent.atomic.AtomicInteger;

public class TestActivity extends Activity {

    static int[] colors = new int[]{Color.GREEN, Color.YELLOW, Color.BLUE,Color.GRAY,Color.RED,Color.BLACK};
    static AtomicInteger index = new AtomicInteger(0);
    static AtomicInteger flag = new AtomicInteger(0);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_main);
        ConstraintLayout view = (ConstraintLayout)findViewById(R.id.testPage);
        Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 0) {
                    switchColor(view);
                }
            }
        };

        Thread t = new Thread(()->{
            while (flag.get()==0){
                try {
                    synchronized (flag) {
                        Message message = new Message();
                        message.obj = "ok";
                        message.what = 0;
                        handler.sendMessage(message);
                        flag.wait(2000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });


        t.start();
        view.setOnClickListener((e)->{
            finish();
        });

    }

    void switchColor (ConstraintLayout view) {
        if (index.get() == colors.length) {
            index.set(0);
        }
        view.setBackgroundColor(colors[index.getAndAdd(1)]);
    }

}
